<script setup lang="ts">
import { onMounted, useTemplateRef } from 'vue';

const usingRef = useTemplateRef<HTMLCanvasElement>('using');
onMounted(() => {
    const canvas = usingRef.value!.querySelector('canvas') as HTMLCanvasElement;
    const ctx = canvas.getContext('2d')!;
    /* 让 canvas 内部像素尺寸与 css 尺寸一致，避免拉伸 */
    const { width, height } = canvas.getBoundingClientRect();
    canvas.width = width;
    canvas.height = height;
    ctx.fillStyle = '#5a8bea';
    ctx.fillRect(0, 0, width, height); // 整屏背景
    // 1. 保存画布状态
    ctx.save();

    // 2. 创建圆形路径作为裁剪区域
    ctx.beginPath();
    ctx.arc(width / 2, height / 2, 160, 0, Math.PI * 2);
    ctx.clip();

    // 3. 清除这块区域（变成透明）
    ctx.clearRect(0, 0, width, height);

    // 4. 恢复状态，后续绘制不再受 clip 影响
    ctx.restore();
});
</script>

<template>
    <div class="using" ref="using">
        我是 Canvas 下的元素（渐变背景）
        <canvas />
    </div>
</template>

<style scoped lang="scss">
.using {
    height: 400px;
    position: relative;
    display: grid;
    place-items: center;
    background: linear-gradient(-45deg, #4d9eff, #ef58a9);
    background-size: 200% 200%;
    animation: background 3s linear infinite;

    // 动画
    @keyframes background {
        0%,
        100% {
            background-position: 0 0;
        }
        50% {
            background-position: 100% 100%;
        }
    }

    canvas {
        position: absolute;
        inset: 0;
        width: 100%;
        height: 100%;
        filter: drop-shadow(0 0 5px rgba(0, 0, 0, 0.81));
    }
}
</style>
